COMP3141
Software System Design and Implementation (18s1)

Code Example (Week 2)

module Week2 where 



-- defines a type alias 
-- the type Point and (Float, Float) can now
-- be used interchangably
type Point = (Float, Float)


addPoint :: Point -> Point -> Point
addPoint (x1, y1) (x2, y2)
  = (x1+x2, y1+ y2)

-- we gave this type to the function in the lecture:
-- fold' :: (a -> a -> a) -> a -> [a] -> a
-- however, in fact, it has a more general type:
fold' :: (a -> b -> b) -> b -> [a] -> b
fold' fn n [] = n
fold' fn n (x : xs) 
  = fn x  (fold' fn n  xs)
-- that is, the two arguments of the function don't 
-- need to be of the same type. They can be (that's 
-- why the type checker accepted our type).
-- Can you find an example application for fold' where
-- 'a' and 'b' are differnt types?



myMap :: (a  ->  b) -> [a] -> [b]
myMap fn [] 
  = [] 
myMap fn  (x:xs) 
  = fn x  : myMap fn xs -- : has a lower precedence than 
                        -- function application,
                        -- so this is the same as  
                        -- (fn x) : (myMap fn xs)

fromTo :: Int -> Int -> [Int]
fromTo start end 
  | end < start = []
  | otherwise   = start : fromTo (start + 1) end

2018-06-14 Thu 18:28

Announcements RSS